<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="文件编码" prop="fileCode">
        <el-input
          v-model="queryParams.fileCode"
          placeholder="请输入文件编码"
          clearable
          @keyup.enter="handleQuery"
          style="width: 215px"
        />
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select
          v-model="queryParams.businessType"
          placeholder="请选择业务类型"
          clearable filterable
          style="width: 215px"
        >
          <el-option
            v-for="dict in file_business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务编码" prop="businessCode">
        <el-input
          v-model="queryParams.businessCode"
          placeholder="请输入业务编码"
          clearable
          @keyup.enter="handleQuery"
          style="width: 215px"
        />
      </el-form-item>
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 215px"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-input
          v-model="queryParams.fileType"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 215px"
        />
        <!-- <el-select
          v-model="queryParams.fileType"
          placeholder="请选择文件类型"
          clearable
          style="width: 215px"
        >
          <el-option
            v-for="dict in dict.type.file_business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['file:fileRecord:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['file:fileRecord:edit']"
          >编辑</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['file:fileRecord:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          
          @click="handleExport"
          v-hasPermi="['file:fileRecord:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="fileRecordList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" width="80" />
      <!-- <el-table-column label="文件编码" align="center" prop="fileCode" /> -->
      <el-table-column label="文件编码" align="center" prop="fileCode">
        <template #default="scope">
          <span class="link-type" @click="handleView(scope.row)">{{
            scope.row.fileCode
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务类型" align="center" prop="businessType">
        <template #default="scope">
          <dict-tag
            :options="file_business_type"
            :value="scope.row.businessType"
          />
        </template>
      </el-table-column>
      <el-table-column label="业务编码" align="center" prop="businessCode" />
      <el-table-column label="文件名称" align="center" prop="fileName" />
      <el-table-column label="文件类型" align="center" prop="fileType" />
      <el-table-column label="文件路径" align="center" prop="filePath" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            icon="Download"
            type="primary"
            @click="handleDownload(scope.row)"
            v-hasPermi="['file:fileRecord:remove']"
            >下载</el-button
          >
          <el-button
            link
            icon="Edit"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['file:fileRecord:edit']"
            >编辑</el-button
          >
          <el-button
            link
            icon="Delete"
            v-if="['MESSAGE'].includes(scope.row.businessType)"
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['file:fileRecord:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件记录对话框 -->
    <el-dialog :title="title" v-model="open" :close-on-click-modal="false" width="650px" append-to-body>
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="文件编码" prop="fileCode">
          <el-input
            v-model="form.fileCode"
            placeholder="请输入文件编码"
            disabled
            style="width: 540px"
          />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-select
            v-model="form.businessType"
            placeholder="请选择业务类型"
            clearable filterable
            style="width: 540px"
          >
            <el-option
              v-for="dict in file_business_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文件名称" prop="fileName">
          <el-input
            v-model="form.fileName"
            placeholder="请输入文件名称"
            disabled
            style="width: 540px"
          />
        </el-form-item>
        <el-form-item label="业务编码" prop="businessCode">
          <el-input
            v-model="form.businessCode"
            placeholder="请输入业务编码"
            clearable
            @keyup.enter="handleQuery"
            style="width: 540px"
          />
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-input
            v-model="form.fileType"
            placeholder="请输入文件类型"
            disabled
            style="width: 540px"
          />
        </el-form-item>
        <el-form-item label="文件路径" prop="filePath">
          <el-input
            v-model="form.filePath"
            placeholder="请输入文件路径"
            disabled
            style="width: 540px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            style="width: 540px"
          />
        </el-form-item>
        <el-form-item label="文件上传" prop="fileList" >
          <el-upload
            ref="upload"
            :limit="1"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            style="width: 540px"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-change="handleFileChange"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-remove="handleFileRemove"
            :auto-upload="false"
            :file-list="form.fileList"
            drag
          >
            <i class="Upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <!-- <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改文件记录对话框 -->
    <el-dialog
      class="fileDialog"
      title="查看文件"
      v-model="openFile"
      width="80%"
      height="80%"
      append-to-body
    >
      <iframe :src="urlFile" width="100%" height="100%"></iframe>
      <!-- <el-image
    style="width: 100px; height:100px"
    :src="urlFile"
    :preview-src-list="[urlFile]">
  </el-image>
  <img :src="urlFile" alt=""> -->
      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { Base64 } from "js-base64";
import {
  listFileRecord,
  getFileRecord,
  updateFileRecord,
  delFileRecord,
  uploadFile,
} from "@/api/file/fileRecord";

export default {
  name: "FileRecord",
  data() {
    return {
      urlFile: null,
      openFile: false,
      fileList: [],
      file: null,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: import.meta.env.VITE_APP_BASE_API + "/file/upload",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件记录表格数据
      fileRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileCode: null,
        businessType: null,
        businessCode: null,
        fileName: null,
        fileBucket: null,
        fileType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fileCode: [
          { required: false, message: "文件编码不能为空", trigger: "blur" },
        ],
        businessType: [
          { required: true, message: "业务类型不能为空", trigger: "change" },
        ],
        businessCode: [
          { required: true, message: "业务编码不能为空", trigger: "change" },
        ],
        fileName: [
          { required: true, message: "文件名称不能为空", trigger: "blur" },
        ],
        fileBucket: [
          { required: true, message: "文件存储桶不能为空", trigger: "change" },
        ],
        fileType: [
          { required: true, message: "文件类型不能为空", trigger: "change" },
        ],
        fileList: [
          { required: false, message: "文件不能为空", trigger: "change" },
        ],
      },
      file_business_type: [],
    };
  },
  created() {
    const { proxy } = getCurrentInstance();
    const { file_business_type } = proxy.useDict("file_business_type");

    this.file_business_type = file_business_type;
    this.getList();
  },
  methods: {
    /** 查询文件记录列表 */
    getList() {
      this.loading = true;
      listFileRecord(this.queryParams).then((response) => {
        this.fileRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        fileCode: null,
        businessType: null,
        businessCode: null,
        fileName: null,
        fileBucket: null,
        filePath: null,
        fileType: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deptId: null,
      };
      this.resetForm("form");
    },
    handleView(row) {
      console.log(row, "handleView===row");
      let rowUrl = "";
      let that = this;
      getFileRecord(row.id).then((response) => {
        rowUrl = response.data.url;
        let url =
          "http://kkfileview-crchem0604-default.crsems-uat.crc.com.cn/kkfileview/onlinePreview?url=" +
          encodeURIComponent(Base64.encode(rowUrl));
        that.openFile = true;
        that.urlFile = url;
        // window.open(url);
        console.log(url, "========");
      });
      // function base64Encode(str) {
      //   var keyStr =
      //     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
      //   var output = "";
      //   var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
      //   var i = 0;
      //   str = utf8Encode(str);
      //   while (i < str.length) {
      //     chr1 = str.charCodeAt(i++);
      //     chr2 = str.charCodeAt(i++);
      //     chr3 = str.charCodeAt(i++);
      //     enc1 = chr1 >> 2;
      //     enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      //     enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      //     enc4 = chr3 & 63;
      //     if (isNaN(chr2)) {
      //       enc3 = enc4 = 64;
      //     } else if (isNaN(chr3)) {
      //       enc4 = 64;
      //     }
      //     output =
      //       output +
      //       keyStr.charAt(enc1) +
      //       keyStr.charAt(enc2) +
      //       keyStr.charAt(enc3) +
      //       keyStr.charAt(enc4);
      //   }
      //   return output;
      // }
    },
    handleDownload(row) {
      console.log(row, "handleView===row");
      let rowUrl = "";
      getFileRecord(row.id).then((response) => {
        rowUrl = response.data.url;
        window.open(rowUrl);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.$refs.upload.clearFiles();
      this.open = true;
      this.title = "添加文件记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // this.$refs.upload.clearFiles();
      const id = row.id || this.ids;
      getFileRecord(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑文件记录";
        this.form.fileList = [
          { name: response.data.fileName, url: response.data.url },
        ];
      });
    },
    /** 提交按钮 */
    submitForm() {
      // this.$refs.upload.submit();
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            if (this.file) {
              const formData = new FormData();
              const param = this.form;
              const blob = new Blob([JSON.stringify(param)], {
                type: "application/json",
              });
              formData.append("file", this.file.raw);
              formData.append("sysFileRecord", blob);
              let config = {
                timeout: 30000,
                headers: { "Content-Type": "multipart/form-data" }, //这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
              };
              uploadFile(formData, config).then((response) => {
                this.$modal.msgSuccess("编辑成功");
                this.open = false;
                this.getList();
              });
            } else {
              updateFileRecord(this.form).then((response) => {
                this.$modal.msgSuccess("编辑成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            if (!this.file) {
              this.$modal.msgError("文件上传不能为空！");
              return false;
            }
            const formData = new FormData();
            const param = this.form;
            const blob = new Blob([JSON.stringify(param)], {
              type: "application/json",
            });
            formData.append("file", this.file.raw);
            formData.append("sysFileRecord", blob);
            let config = {
              timeout: 30000,
              headers: { "Content-Type": "multipart/form-data" }, //这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
            };
            uploadFile(formData, config).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除所选文件记录？")
        .then(function () {
          return delFileRecord(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    beforeUpload(file) {
      console.log(file, "===beforeUpload===file");
    },
    handlePreview(file) {
      console.log(file);
      if (file.url) {
        let url =
          "http://kkfileview-crchem0604-default.crsems-uat.crc.com.cn/kkfileview/onlinePreview?url=" +
          encodeURIComponent(Base64.encode(file.url));
        this.openFile = true;
        this.urlFile = url;
      }
    },
    handleFileChange(file, fileList) {
      this.file = file;
      this.form.fileName = file.name;
      this.form.fileType = file.name.substr(file.name.indexOf(".") + 1);
      console.log(file, fileList, "===beforeUpload===file");
      this.form.fileList = fileList;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      console.log(response, file, fileList, "=======");
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log(response, file, fileList, "=======");
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      // this.getList();
    },
    handleFileRemove(file, fileList) {
      console.log(file, fileList, "handleFileRemove===file, fileList");
      this.file = "";
      this.form.fileList = [];
      this.form.fileName = "";
      this.form.fileType = "";
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "file/fileRecord/export",
        {
          ...this.queryParams,
        },
        `fileRecord_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.fileDialog {
  :deep(.el-dialog) {
    height: 88%;
  }
  :deep(.el-dialog__body) {
    height: 94%;
  }
}
</style>
